from django.shortcuts import render
from rest_framework.views import APIView
from app01.models import Book
from app01.ser import BookSerializer, BookModelSerializer
from rest_framework.response import Response
from app01.utils import MyResponse

# Create your views here.


class BookView(APIView):
    def get(self, request, pk):
        book = Book.objects.filter(id=pk).first()
        book_ser = BookSerializer(book)  # serializer: <class 'app01.ser.BookSerializer'>
        print('serializer:', type(book_ser))
        return Response(book_ser.data)  # drf提供的response对象 继承了HttpResponse
        # Response(serializer_obj.data)  # 固定写法  序列化后的字典

    def put(self, request, pk):
        response_msg = {'status': 100, 'msg': '成功'}
        book = Book.objects.filter(id=pk).first()
        # 得到一个序列化类的对象
        book_ser = BookSerializer(instance=book, data=request.data)
        # 用request.data修改这个book对象
        # 要数据验证
        if book_ser.is_valid():
            book_ser.save()  # 直接save会报错,要重写update方法, 不要用book.save() 不是orm提供的而是rest_framework提供的
            response_msg['data'] = book_ser.data
        else:
            response_msg['data'] = book_ser.errors
            response_msg['status'] = 101
            response_msg['msg'] = '数据校验失败'
        return Response(response_msg)

    def delete(self, request, pk):
        response_msg = {'status': 100, 'msg': '删除成功'}
        ret = Book.objects.filter(id=pk).delete()
        return Response(response_msg)


class BooksView(APIView):
    def get(self, request):
        response = MyResponse()
        books = Book.objects.all()
        book_ser = BookSerializer(books, many=True)  # many=True 序列化多条
        print('serializer_many:', type(book_ser))
        # serializer_many: <class 'rest_framework.serializers.ListSerializer'>
        response.data = book_ser.data
        return Response(response.get_dict)

    def post(self, request):
        response_msg = {'status': 100, 'msg': '成功'}
        # 修改才有instance，新增没有instance，只有data
        book_ser = BookSerializer(data=request.data)
        # 教研制度按
        if book_ser.is_valid():
            book_ser.save()
            response_msg['data'] = book_ser.data
        else:
            response_msg['status'] = 102
            response_msg['msg'] = '数据校验失败'
            response_msg['data'] = book_ser.errors
        return Response(response_msg)


class BooksView2(APIView):
    def get(self, request):
        response = MyResponse()
        books = Book.objects.all()
        book_ser = BookModelSerializer(books, many=True)
        print('model_serializer', type(book_ser))
        # model_serializer <class 'rest_framework.serializers.ListSerializer'>
        response.data = book_ser.data
        return Response(response.get_dict)